package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;

    /**
     * 获取openId
     * @param code
     * @return openId
     */
    @Override
    public String getOpenid(String code){
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code", code);

        String s = HttpUtil.get(REQUEST_URL, map);

        JSONObject jsonObject = JSONUtil.parseObj(s);
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.get("errmsg").toString());
        }
        String openid = jsonObject.getStr("openid");

        return openid;
    }

    /**
     * 获取手机号
     * @param phoneCode
     * @return 手机号
     */
    @Override
    public String getPhone(String phoneCode){
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);

        //1,获取assess_token
        String s = HttpUtil.get(TOKEN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        String accessToken = (String) jsonObject.get("access_token");

        //获取手机号
        Map<String, Object> phoneMap = new HashMap<>();
        phoneMap.put("code", phoneCode);
        String post = HttpUtil.post(PHONE_REQUEST_URL + accessToken, JSONUtil.toJsonStr(phoneMap));

        JSONObject phoneObject = JSONUtil.parseObj(post);
        if (phoneObject.getInt("errcode") != 0){
            throw new BaseException(phoneObject.get("errmsg").toString());
        }

        JSONObject phoneInfo = (JSONObject) phoneObject.get("phone_info");
        String phone = phoneInfo.get("phoneNumber").toString();
        return phone;
    }
}
